from django.shortcuts import render,redirect
from django.http import JsonResponse
from web import models
from stark.utils.md5 import rev_md5
from rbac.service.init_permissions import init_permissions


def login(request):
    if request.is_ajax():
        # 获取用户名密码，和数据库里的验证
        user = request.POST.get('user')
        pwd = rev_md5(request.POST.get('pwd'))
        current_user = models.UserInfo.objects.filter(name=user, password=pwd).first()
        status = {'flag': False}
        if current_user:
            # 调用 初始化权限函数，获取权限，写入session
            request.session['current_user'] = current_user.nickname
            request.session['current_user_id'] = current_user.pk
            status['msg'] = True
            init_permissions(current_user,request)
        return JsonResponse(status)
    return render(request, 'login.html')


def logout(request):
    request.session.flush()
    return redirect('/login/')

def index(request):
    if not request.session.get('current_user'):
        return redirect('/login/')
    return render(request,'index.html')